<template>
  <div>
    <el-dialog v-model="formDelete.dialog" title="确认" width="30%" center>
      <template #default>
        <div class="action_tip">
          您将删除:{{ formDelete.name }}
        </div>
      </template>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="formDelete.dialog = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="formEdit.dialog" title="修改" width="40%" center>
      <el-form-item>
        <el-upload
            :limit="1"
            ref="upload"
            v-model:file-list="fileList"
            action="/api/file/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :auto-upload="true"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image"/>
        </el-dialog>
      </el-form-item>
      <el-form :rules="rules" :model="formEdit" :inline="true"  v-loading="loading">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formEdit.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称"  prop="nickname">
          <el-input v-model="formEdit.nickname"></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input v-model="formEdit.email"></el-input>
        </el-form-item>
        <el-form-item label="企业">
          <el-input v-model="formEdit.enterpriseName"></el-input>
        </el-form-item>
        <el-form-item label="企业联系方式">
          <el-input v-model="formEdit.contact"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formEdit.phone"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="formEdit.dialog=false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="formAdd.dialog" title="添加" width="40%" center>
      <el-form-item>
        <el-upload
            :limit="1"
            ref="upload"
            v-model:file-list="fileList"
            action="/api/file/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :auto-upload="true"
        >
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image"/>
        </el-dialog>
      </el-form-item>
      <el-form :model="formAdd" :inline="true" :rules="rules">
        <el-form-item label="姓名"  prop="name">
          <el-input v-model="formAdd.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称"  prop="nickname">
          <el-input v-model="formAdd.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户名"  prop="username">
          <el-input v-model="formAdd.username"></el-input>
        </el-form-item>
        <el-form-item label="密码"  prop="password">
          <el-input type="password" v-model="formAdd.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="formAdd.email"></el-input>
        </el-form-item>
        <el-form-item label="企业">
          <el-input v-model="formAdd.enterpriseName"></el-input>
        </el-form-item>
        <el-form-item label="企业联系方式">
          <el-input v-model="formAdd.contact"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formAdd.phone"></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="formAdd.dialog=false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
      </span>
      </template>
    </el-dialog>

    <div class="button_add">
      <el-button type="primary" @click="addLog">
        <el-icon>
          <Plus></Plus>
        </el-icon>
        添加
      </el-button>
      <!--      <el-button type="primary" @click="editLog(null)">添加</el-button>-->
      <el-input v-model="search.name"
                placeholder="输入姓名查询">
      </el-input>
      <el-input v-model="search.nickname"
                placeholder="输入昵称查询">
      </el-input>
      <el-input v-model="search.phone"
                placeholder="输入手机号查询">
      </el-input>
      <el-button type="primary" @click="getTableData">
        <el-icon>
          <Search></Search>
        </el-icon>
        查询
      </el-button>
      <el-button @click="refreshTable">
        <el-icon>
          <Refresh></Refresh>
        </el-icon>
        重置
      </el-button>
    </div>
    <el-scrollbar>
      <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" border
                 stripe :data="tableData">

        <el-table-column >
          <template #default="scopeEdit">
            <el-image :src="'/api/file/img?name='+scopeEdit.row.img">
            </el-image>
          </template>
        </el-table-column>

        <el-table-column prop="userId" label="编号" width="auto"/>
        <el-table-column prop="name" label="姓名" width="auto"/>
        <el-table-column prop="email" label="邮箱" width="auto"/>

        <el-table-column prop="nickname" label="昵称" width="auto"/>
        <el-table-column prop="phone" label="手机号" width="auto"/>
        <el-table-column prop="createTime" label="创建时间" width="auto"/>
        <el-table-column prop="enterpriseName" label="企业" width="auto"/>
        <el-table-column prop="contact" label="企业联系方式" width="auto"/>

        <el-table-column fixed="right" label="操作">
          <template #default="scopeEdit">
            <el-button
                type="danger"
                size="small"
                @click.prevent="deleteLog(scopeEdit.row.userId,scopeEdit.row.name)">
              <el-icon>
                <Delete/>
              </el-icon>
              <span>删除</span>
            </el-button>
            <el-button
                type="primary"
                size="small"
                @click.prevent="editLog(scopeEdit.row.id,scopeEdit.row.userId)">
              <el-icon>
                <Edit/>
              </el-icon>
              <span>编辑</span>
            </el-button>
          </template>
        </el-table-column>

      </el-table>
    </el-scrollbar>

  </div>
</template>

<script lang="ts" setup>

import {onMounted, reactive, ref, watch} from "vue";
import {Delete, Edit, Download, ZoomIn, Plus, Refresh, Search} from '@element-plus/icons-vue'

import {

  deleteUserByUserIdApi,

  getEnUserByNameApi,
  getEnUserInfoByIdApi, updateInfo, addUserApi, addEnUser, updateEnUserInfo,
} from "@/api/admin";
import {ElMessage, genFileId, UploadInstance, UploadRawFile} from "element-plus";

import {closeLoading, showLoading, showTips, successTips, warningTips} from "@/utils/util";
import type {UploadProps, UploadUserFile} from 'element-plus'

const fileList = ref<UploadUserFile[]>([] as any)

const upload = ref<UploadInstance>()

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
//数据初始化
onMounted(() => {
  getTableData()
})
const rules= {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  region: [
    { required: true, message: '请选择活动区域', trigger: 'change' }
  ],
  date1: [
    { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
  ],
  date2: [
    { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
  ],
  type: [
    { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
  ],
  resource: [
    { required: true, message: '请选择活动资源', trigger: 'change' }
  ],
  desc: [
    { required: true, message: '请填写活动形式', trigger: 'blur' }
  ]
}


const tableData = ref([])
const loading = ref(true)
const search = reactive({
  nickname: "",
  phone: "",
  name: "",
})

function refreshTable() {
  Object.assign(search, {
    nickname: "",
    phone: "",
    name: "",
  })
  getTableData()
}

function getTableData() {
  getEnUserByNameApi(search).then((response: any) => {
    if (response.code === 200) {
      tableData.value = response.data
    } else {
      ElMessage.warning(response.msg)
    }
    loading.value = false
  }).catch(function (res: any) {
    loading.value = false
    ElMessage.error("页面加载失败")
  })
}


//添加修改数据初始化
const formAdd = reactive({
  username: "",
  name: "",
  role: 1,
  nickname: "",
  sex: 0,
  phone: "",
  email: "",
  enterpriseName: "",
  contact: "",
  password: "",
  img: "",
  dialog: false
})

function addLog(id: any, userId: any) {
  let formRaw = {
    username: "",
    name: "",
    role: 1,
    nickname: "",
    sex: 0,
    phone: "",
    email: "",
    enterpriseName: "",
    contact: "",
    password: "",
    img: "",
    dialog: true
  }
  Object.assign(formAdd, formRaw)
}
interface ResponseData {
  // 这里定义 response.data 的具体结构
  url: string;
  // 其他字段...
}
function confirmAdd() {
  if (formAdd.username.trim() == '') {
    warningTips("用户名不可为空")
    return
  }
  if(fileList.value.length>0){
    const response = fileList.value[0].response as { data: ResponseData };
    formAdd.img = response.data as any;
  }
  addEnUser(formAdd).then((response: any) => {
    if (response.code === 200) {
      successTips(response.message)
      Object.assign(formAdd, {
        enterprise: "",
        enterpriseContact: "",
        username: "",
        name: "",
        role: 1,
        nickname: "",
        img: "",
        sex: 0,
        phone: "",
        email: "",
        dialog: false
      })
    } else {
      warningTips(response.message)
    }
    loading.value = false
    formEdit.dialog = false
    getTableData()
  })
}


const formEdit = reactive({
  id: '',
  userId: '',
  // username: "",
  name: "",
  role: 1,
  nickname: "",
  // password: "",
  sex: 0,
  phone: "",
  email: "",
  img: "",
  enterpriseName: "",
  contact: "",
  dialog: false
})

function editLog(id: any, userId: any) {
  fileList.value = []
  let formRaw = {
    id: '',
    userId: userId,
    username: "",
    name: "",
    role: 1,
    nickname: "",
    sex: 0,
    phone: "",
    img: "",
    email: "",
    enterprise: "",
    enterpriseContact: "",
    dialog: true
  }
  if (id) {
    getEnUserInfoByIdApi(formRaw).then((response: any) => {
      Object.assign(formRaw, response.data[0])
      Object.assign(formEdit, formRaw)
    })
  } else {
    Object.assign(formEdit, formRaw)
  }
}

function confirmEdit() {
  if(fileList.value.length>0){
    const response = fileList.value[0].response as { data: ResponseData };
    console.log(response)
    formEdit.img = response.data as any;
  }

  updateEnUserInfo(formEdit).then((response: any) => {
    if (response.code === 200) {
      successTips(response.message)
    } else {
      warningTips(response.message)
    }
    loading.value = false
    formEdit.dialog = false
    getTableData()
  })
}

function Cancel() {
  formEdit.dialog = false;
}


const formDelete = reactive({
  id: null,
  name: '',
  dialog: false
})


function deleteLog(userId: any, name: any) {
  Object.assign(formDelete, {
    userId: userId,
    name: name,
    dialog: true
  })

}

function confirmDelete() {
  showLoading()
  deleteUserByUserIdApi(formDelete)
      .then(function (response: any) {
        getTableData()
        formDelete.dialog = false
        ElMessage.success(response.message)
        closeLoading()
      })
}
</script>
